package dataStructure.Stack;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @author lhn
 * @date 2024-09-12 20:44
 */

public class ReversePolishNotation {
    public static void main(String[] args) {
        String expression = "36 4 + 5 * 6 -";
        System.out.println(calculate(expression));
    }

    public static List<String> getListString(String expression) {
        String[] split = expression.split(" ");
        List<String> list = new ArrayList<String>();
        for (String s : split) {
            list.add(s);
        }
        return list;
    }

    public static int calculate(String expression) {

        List<String> expressionList = getListString(expression);

        Stack stack = new Stack();

        while (expressionList.size() > 0) {
            String s = expressionList.remove(0);
            if (
                    "+".equals(s) ||
                            "-".equals(s) ||
                            "*".equals(s) ||
                            "/".equals(s)
            ) {
                int num1 = Integer.parseInt(stack.pop().toString());
                int num2 = Integer.parseInt(stack.pop().toString());
                int res = 0;
                res = cal(num1, num2, s);
                stack.push(res);
            } else {
                stack.push(s);
            }
        }
        return (int) stack.pop();
    }

    public static int cal(int num1, int num2, String operator) {
        int res = 0; //result
        //后弹出的数 operator 先弹出的数
        switch (operator) {
            case "+":
                res = num1 + num2;
                break;
            case "-":
                res = num2 - num1;  //顺序
                break;
            case "*":
                res = num1 * num2;
                break;
            case "/":
                if (num1 == 0) {
                    throw new RuntimeException("表达式有问题");
                }
                res = num2 / num1;
                break;
        }
        return res;
    }
}
